package org.yx.service.sbas.save_supplier_roster;

import com.xiaoleilu.hutool.util.StrUtil;
import org.yx.exception.BizException;
import org.yx.models.SbasSupDef;
import org.yx.service.bas.create_rule_code.BasCreateRuleCodeService;
import org.yx.utils.BaseService;
import org.yx.utils.FieldMap;

/**
 * 保存供应商信息
 * @author zxw
 * @since 2018/03/27
**/
public class SbasSaveSupplierRosterService extends BaseService {
	private final static String SUP_CODE="SUPPLIER";

	public SbasSaveSupplierRosterOut saveSupplierRoster(SbasSaveSupplierRosterIn in) throws Exception {
		checkStringNotBlank(in, "supName");

		SbasSupDef oldSup = selectWithPk(SbasSupDef.class, in.getUserOrgCode(), in.getSupCode());
		SbasSupDef sup = new SbasSupDef();
		if (oldSup != null) {
			if (new Character('D').equals(oldSup.getStatus())) {
				throw new BizException("SBAS-0003", new FieldMap("supCode", oldSup.getSupCode()));
			}

			if (new Character('D').equals(in.getStatus())) {
				oldSup.setStatus(in.getStatus());

				update(oldSup, "status");
			} else {
				copyProperties(oldSup, sup);
				copyProperties(in, sup);
				if (in.getStatus() == null) {
					sup.setStatus('N');
				}

				update(sup);
			}
		} else {
			copyProperties(in, sup);
			sup.setOrgCode(in.getUserOrgCode());
			sup.setStatus('N');
			if(StrUtil.isBlank(in.getSupCode())){
				sup.setSupCode(BasCreateRuleCodeService.createRuleCode(SUP_CODE));
			}

			insert(sup);
		}

		SbasSaveSupplierRosterOut out = new SbasSaveSupplierRosterOut();

		return out;
	}
}